<template>
  <div class="all">
    <div v-if="$route.query.guoqi" class="goBack" @click="go"></div>
    <header>
      <div v-if="Codetypes=='present'">礼品券店内自提</div>
      <div v-if="Codetypes=='ticket'">票务店内自提</div>
      <div v-if="Codetypes=='cash'">代金券店内自提</div>
      <div v-if="Codetypes=='voucher'">抵用券店内自提</div>
      <div v-if="Codetypes=='rebate'">折扣券店内自提</div>
      <div>共{{length}}张</div>
    </header>
    <div style="background:#f5f5f5;padding-left: 1rem;">
      <div class="couponDiv">
        <coupon-denomination :item="couponParam"></coupon-denomination>
      </div>
      <div style="margin-left: 4rem;position: relative;top: .3rem;">{{name}}</div><br />
      <div style="margin-left: 4rem;position: relative;top: -.3rem;color: #999;font-size: .9rem;">{{mchtName}}</div><br />
      <div style="margin-left: 4rem;position: relative;top: -1rem;color: #999;font-size: .9rem;">有效期:{{info.validatyBegin|strDate(3)}}至{{info.validatyEnd|strDate(3)}}</div>
    </div>
    <div class="content">
      <div class="swiperCon" style="height: 280px;">
        <mt-swipe style='height: 300px;background: white;' :show-indicators="false" :auto="0" :continuous="false" @change="handleChange">
          <mt-swipe-item style='height: 300px;margin: 0;' v-for='(item,index) in couNoMarry' :key='index'>
           <div style="margin: 0 auto;text-align: center;"><svg class ='barcode'></svg></div>
            <!--<div style="margin: 0 auto;text-align: center;width: 100%;font-size: .9rem;color: #ee5088;height: 2rem;" @click="$router.push({path:'/codeRotate',query:{num:shuzis,Codetypes:Codetypes}})">（点击查看条形码）</div>-->
            <div style="height: 20px;margin: 0 auto;text-align: center;color: #666666;font-size: .9rem;" v-if="!xianshi" @click="$router.push({path:'/codeRotate',query:{num:shuzis,Codetypes:Codetypes}})">{{shuzi}}*****查看数字</div>
            <div style="height: 1rem;margin: 0 auto 1rem;text-align: center;" v-if="xianshi" >{{shuzis}}</div>
            <div style="width: 130px;height: 130px;margin: 4rem auto;overflow: hidden;" class="qrcode" @click="code"></div>

          </mt-swipe-item>
        </mt-swipe>
      </div>
      <p v-if="moreCouponState">向左滑动可以使用更多券</p>
      <p v-if="!moreCouponState"></p>
      <p v-if="moreCouponState">{{num}}({{length}})</p>
      <p v-if="!moreCouponState"></p>
      <p style="height: 3rem;color: #ffffff;background: #f6577f;line-height: 3rem;position: absolute;bottom: 0;width: 100%;" @click="firmOrder" v-if="Codetypes=='ticket'||Codetypes=='present'">算了，还是给我寄回来吧</p>
    </div>
    <div id="aaaaaa" class="right" @click="code" v-if="moreCouponState" v-show="false"></div>
    <div class="shadowDiv" v-if='orderId'></div>
    <div v-if='comment' class="neirong">
      <div class="prompt">提示</div>
      <div class="promptContent">核销成功，是否评一评</div>
      <div class="btnDiv">
        <span class="cancelBtn" @click="quxiao">取消</span>
        <span class="confirmBtn" @click="goComment">确定</span>
      </div>
    </div>
    <!-- 奖励显示弹框 -->
   <reward-modal v-if="shareInfo" @close="hiddenShareInfo" :stateUnder="stateUnder" :moneyUnder1="moneyUnder1" :moneyUnder2="moneyUnder2" :money="usrAmt" :nums="nums" type="use" returnHistory='true'></reward-modal>
  </div>
</template>

<script>
  import header from '../../componentes/global/header.vue'
  import * as types from '../../vuex/types.js'
  import RewardModal from 'src/componentes/global/reward/index.vue'
  import {
    Swipe,
    SwipeItem
  } from 'mint-ui';
  import {
    mapState
  } from 'vuex'
  import getData from '../../service/getData.js'
  import couponNum from '../../componentes/global/couponNum.vue'
  import cardList from './cardList.vue'
  import 'src/assets/js/qrcode.js';
  import {
    socket
  } from '../../utils/socket'
  import {
    Toast,
    Indicator,
    MessageBox
  } from 'mint-ui'
  import {
    Storage
  } from 'src/utils/storage.js'
  var JsBarcode = require('jsbarcode');
  export default {
    name: 'useYunConpons',
    components: {
      cardList,
      RewardModal
    },
    data() {
      return {
        swiperOption: {
          autoplay: 3000,
          direction: 'horizontal',
          setWrapperSize: true,
          autoHeight: true,
          pagination: '.swiper-pagination',
          debugger: true,
          loop: true,

        },

        Codetypes: '',
        name: '',
        mchtName: '',
        soldnum: '',
        usednum: '',
        mchtId: '',
        length: '',
        moreCouponState:false,
        num: 1, //轮播滚动使用变化，
        strCode: '', //二维码编码
        //             tlrNo:'',
        denomination: '',
        couponId: '',
        couNoMarry: [],
        couNo: '',
        socket: () => {},
        tt: () => {}, //定时任务，断开webSocket重连
        socketContent: '',
        Num: 0,
        orderId: '',
        couponNos: '',
        mchtIds: '',
        shareInfo:false,
        comment:false,
        usrAmt:0,
        info:Storage.get("info",true),
        couponParam:{},
        shuzi:'',
        shuzis:'',
        xianshi:false,
        nums:1,
			  moneyUnder1:'',
			  moneyUnder2:'',
			  stateUnder:false,

      }
    },
    created: function() {
      // 监视滚动
      window.addEventListener('scroll', this.handleScroll);
      document.body.scrollTop = 0;
      this.$store.commit(types.HEAD_TEXT, "使用礼品券");
      this.$store.commit(types.HEAD_BACK_ICON, true);
      this.$store.commit(types.HEAD_MES_ICON, false);
      this.$store.commit(types.HEAD_BACK_ICON, true);
      this.Codetypes = this.info.Codetypes;
      this.name = this.info.name;
      this.mchtName = this.info.mchtName;
      this.soldnum = this.info.soldnum;
      this.usednum = this.info.usednum;
      this.mchtId = this.info.mchtId;
      this.denomination = this.info.denomination;
      this.couponId = this.info.couponId;
      this.couponParam={type:this.info.Codetypes,denomination:this.info.denomination,}
    },
    mounted: async function() {

      let data = {
        method: 'post',
        data: {
          couponId: this.couponId,
          mchtId: this.mchtId,
          usrId: this.userInfo.usrId
        }

      }
      let code = await getData.findCode(data)
      if (code.respCode) {

        this.couNoMarry = JSON.parse(code.content).couponNos.split(',')
        console.log(this.couNoMarry)
        this.length = this.couNoMarry.length
        if( this.couNoMarry.length!=1){
        	this.moreCouponState=true
        }else{
        	this.moreCouponState=false
        }
      }
      this.$nextTick(function() {
        this.qrcodeEvent();
        const me = this;
        this.socket = socket(process.env.SOCKET_API + "/web/socketServer/", this.userInfo.usrId);
        //定时查询webSocket是否断开，断开则重连。
        this.tt = setInterval(() => {
          //判断webSocket是否存在或不在通信状态则进行重新连接并重新建立监听事件
          if (!me.socket || me.socket.readyState !== 1) {
            me.socket.removeEventListener("message", this.messageListen, false); //删除监听事件
            me.socket = socket(process.env.SOCKET_API + "/web/socketServer/", me.userInfo.usrId);
            me.socket.addEventListener("message", me.messageListen, false); //监听message事件
          }
        }, 2500);
        me.socket.addEventListener("message", me.messageListen, false); //监听message事件
//      	 setTimeout(() =>{
//      	 let a=document.getElementsByTagName("img")[0].offsetHeight
//		       document.getElementsByClassName("right")[0].style.top=a
//      	 },100)
        	 
      })
    },
    computed: {
      ...mapState({
        userInfo: state => state.user.userInfo,
        userUrl: state => state.user.userUrl,
      })
    },
    methods: {
      go(){
        this.$router.push({"path":'/expiredDetail/'+this.$route.query.mchtId+'/'+this.$route.query.couponId+'/'+this.$route.query.couponNum,query:{guoqi:true}});
      },
      qrcodeEvent: function() {
        var couNoArr = []
        let me = this;
        console.log(me.couNoMarry)
        me.couNoMarry.forEach((item, index) => {
          couNoArr.push(item)
        })
        console.log(couNoArr)
        var qrcode;
        qrcode = new QRCode(document.getElementsByClassName("qrcode")[0], {
          width: 130, //设置宽高
          height: 130
        });

        //qrcode.makeCode(me.userInfo.usrId + '');
        //二维码生成初始第一张
        var usr = {};
        console.log(me.couNo)
        usr.usrId = me.userInfo.usrId
        usr.usrId = this.userInfo.usrId
        usr.couNo = couNoArr[0]
        this.shuzi=usr.couNo.substring(0,4)
        this.shuzis=usr.couNo
        usr.couponId = me.couponId
        usr.mchtId = me.mchtId
        //确认订单传数据
        Storage.set('firmOrder', {
          couponId: usr.couponId,
          mchtId: usr.mchtId,
          type: this.Codetypes,
          num: this.length
        })
        //              getDate4.getUsrInfo({usrId: this.userInfo.usrId}).then(function(rep){
        //        	me.tlrNo=rep.content.usr.tlrNo
        var strr = 'YQ://P=00&SC=05&V={"a":"' + usr.couNo + ',' + usr.couponId + ',' + usr.usrId + ',' + usr.mchtId + ',' + me.Codetypes + '"}'
        qrcode.makeCode(strr);
        //        })
        JsBarcode(".barcode", usr.couNo,{width:1,height:45,  displayValue:false});

      },

      //          切换轮播
      handleChange: function(index) {
        var couNoArr1 = []
        var me = this
        me.couNoMarry.forEach((item, index) => {
          couNoArr1.push(item)
        })
        this.num = index + 1
        //二维码生成根据轮播动态生成
        var qrcode;
        qrcode = new QRCode(document.getElementsByClassName("qrcode")[index], {
          width: 130, //设置宽高
          height: 130
        });

        var usr = {};
        usr.usrId = this.userInfo.usrId
        usr.couNo = couNoArr1[0]
        usr.couponId = me.couponId
        var str = 'YQ://P=00&SC=05&V={"a":"' + couNoArr1[index] + ',' + usr.couponId + ',' + usr.usrId + ',' + me.mchtId + ',' + me.Codetypes + '"}'
        qrcode.makeCode(str);
        me.shuzi=couNoArr1[index].substring(0,4)
        me.shuzis=couNoArr1[index]
        JsBarcode(".barcode", couNoArr1[index],{width:1,height:45,  displayValue:false});

        if (index = 1) {
          document.getElementsByClassName("right")[0].style.opacity = "0"
        }
      },
      code: function() {
        document.getElementsByClassName("right")[0].style.opacity = "0"
      },
      messageListen(evt) {
        this.socketContent = JSON.parse(evt.data);
        if (this.socketContent) {
          var me = this
          me.usrAmt = (me.socketContent[0].usrAmt+ me.socketContent[0].settUsrAmt).toFixed(2)
          me.orderId = me.socketContent[0].orderId
          me.couponNos = me.socketContent[0].couNo
          me.mchtIds = me.socketContent[0].mchtId
					if (me.socketContent[0].usrAmt==0&&me.socketContent[0].settUsrAmt==0) {
						 me.comment = true;
						me.shareInfo = false
			
					}else if(me.socketContent[0].usrAmt>0&&me.socketContent[0].settUsrAmt>0){
						me.shareInfo = true
						me.moneyUnder1=me.socketContent[0].usrAmt
						me.moneyUnder2=me.socketContent[0].settUsrAmt
						me.nums=2
						me.stateUnder=true
					}else{
						me.shareInfo = true
						me.stateUnder=false
					}
        }
      },
      hiddenShareInfo(){
        this.shareInfo = false;
        this.comment = true;
      },
      firmOrder: function() {
        var me = this
        if (me.Codetypes !== 'present' && me.Codetypes !== 'ticket') {
          Toast({
            message: "该券暂时不可邮寄",
            duration: 800
          });
          return
        }
        getData.findCode({
          method: 'post',
          data: {
            couponId: this.couponId,
            mchtId: this.mchtId,
            usrId: this.userInfo.usrId

          }
        }).then(function(rep) {
          if (JSON.parse(rep.content).couponNos.split(',')[0] == '') {
            Toast({
              message: "您没有可用的券",
              duration: 800
            });
          } else if (JSON.parse(rep.content).couponNos.split(',')[0] != '') {
            me.$router.push({
              'name': 'firmOrder'
            })
          }

        })
        //      	if(this.socketContent!=''){
        //      		Toast({
        //	                      message: "您已经使用过二维码，不可以邮寄",
        //	                      duration: 800
        //                 	});
        //      	}else{

        //      	}
      },
      quxiao() {
        this.$router.replace({
          path: '/cardList',
          query: {
            vueRouterHistory1: 1
          }
        })
      },
      goComment() {
        console.log(this.couponNos)
        if (this.Codetypes == 'present' || this.Codetypes == 'ticket') {
          this.$router.replace({
            name: 'doComment',
            query: {
              mchtId: this.mchtIds,
              couponNos: '',
              orderId: this.orderId
            }
          })
        } else {
          this.$router.replace({
            name: 'doComment',
            query: {
              mchtId: this.mchtIds,
              couponNos: this.couponNos,
              orderId: this.orderId
            }
          })
        }

      }
    },
    beforeDestroy() {
      clearInterval(this.tt); //移除重新连接webSocket定时器
      this.socket.removeEventListener("message", this.messageListen, false); //删除监听事件
      this.socket.close(); //关闭webSocket
    },
    filters: {
      numRebateF:function(value){
        let _price = value.toString();
        if(_price >= 10){
          var str = _price.slice(0,1);
        }else{
          var str ='0';
        }
        if(_price.slice(1,2)){
          if(_price.slice(1,2)==0){
            return value/10+'.'+0;
          }
        }
        return value/10;
      }
    }
  }
</script>

<style scoped>
  .all {
    background: #FFFFFF;
    height: 100%;
    position: relative;
  }

  header {
    height: 2.9rem;
    background: #f5f5f5;
  }

  header div:nth-of-type(1) {
    float: left;
    line-height: 2.9rem;
    text-indent: 1rem;
    color: #333333;
  }

  header div:nth-of-type(2) {
    float: right;
    line-height: 2.9rem;
    margin-right: 2rem;
    color: #666666
  }

  .content{
  	margin-top: 1rem;
  }
  .content div:nth-of-type(1) {
    height: 4.8rem;
    margin: 0 auto;
  }

  .content p {
    text-align: center;
  }

  .content p:nth-of-type(1) {
    /*margin-top: 2rem;*/
    height: 1.72rem;
    color: #666666;
    font-size: .9rem;
  }

  .content p:nth-of-type(2) {
    height: 2rem;
    color: #333333;
  }

  .content p:nth-of-type(3) {
    color: #666666;
  }

  .content div:nth-of-type(2) {
    margin-top: .4rem;
    height: 130px;
  }

  .content p:nth-of-type(4) {
    height: 1.8rem;
    margin: .4rem 0;
  }

  .content p:nth-of-type(5) {
    height: 3.97rem;
  }

  .content .bottom {
    height: 2rem;
    width: 100%;
    position: absolute;
    bottom: 3rem;
  }

  .content p:nth-of-type(6) {
    width: 100%;
    height: 3rem;
    color: #ec4e8a;
    line-height: 3rem;
    position: absolute;
    bottom: 0;
    text-align: center;
  }

  mt-swipe-item {
    height: 100%;
  }

  mt-swipe-item div {
    background: white;
  }

  .num_price span {
    font-size: 1.4rem;
    color: white;
    font-family: Arial;
    position: relative;
    top: -.3rem;
  }

  .coupontype {
    position: relative;
    top: -3rem;
    font-family: Arial;
    font-size: .8rem;
    color: white;
  }

  .right {
    width: 20px;
    height: 130px;
    background: url(../../images/code2.png);
    position: absolute;
    right: 0;
    top: 17rem;
    opacity: .4;
    transition: opacity 2s;
  }

  .couponDiv {
    /*padding-top: .3rem;*/
  }


  /*提示框*/

  .shadowDiv {
    width: 100vw;
    height: 100vh;
    background: gray;
    opacity: .5;
    position: absolute;
    left: 0;
    top: 0;
  }

  .prompt {
    height: 3rem;
    line-height: 3rem;
    text-align: center;
    font-size: 1.2rem;
  }

  .promptContent {
    height: 3rem;
    line-height: 3rem;
    text-align: center;
    color: gray;
  }

  .btnDiv {
    width: 100%;
    border-top: 1px solid gainsboro;
  }

  .cancelBtn {
    width: 50%;
    height: 3rem;
    line-height: 3rem;
    text-align: center;
    color: gray;
    float: left;
    border-right: 1px solid gainsboro;
    box-sizing: border-box;
    display: block;
  }

  .confirmBtn {
    width: 50%;
    height: 3rem;
    line-height: 3rem;
    text-align: center;
    color: cornflowerblue;
    float: right;
    display: block;
  }
  .goBack{

    z-index: 30;
    position: absolute;
    left: 0;
    top: -4rem;
    width: 50px;
    height: 50px;

  }
  .neirong {
    position: absolute;
    left: 10%;
    width: 80%;
    height: 9rem;
    top: 30%;
    border: 1px solid gainsboro;
    box-sizing: border-box;
    background: white;
  }

</style>
